let router =require('koa-router')();
let fs =require('fs');
let path =require('path');

function searchController(dir){
    let files =fs.readdirSync(__dirname);
    let fileCon =files.filter((name)=>{
        return name.endsWith('.js') && name !== 'index.js';
    })
    return fileCon;
}

function registerController(files){
    files.forEach((item)=>{
        let tpmPath =path.join(__dirname,item);
        let route =require(tpmPath);

        for(let url in route){
            let type =route[url][0];
            let fn =route[url][1];

            if(type === 'get'){
                router.get(url,fn);
            } else{
                router.post(url,fn);
            }
        }
    })
}

module.exports =function(currentDir){
    let dir =currentDir || __dirname;
    let tmp =searchController(dir);
    registerController(tmp);
    return router.routes();
}